#include <iostream>
#include <pthread.h>
#include <cstdio>
#include <unistd.h>
#include <string.h>
#include <string>

/* void* handler(void* argv)
{  
    std::string message = (char*)argv;
    while (true)
    {   
        std::cout << "My name is " << message << " , my pid is " << getpid() << std::endl;
        sleep(1);
    }
    return nullptr;
}


int main()
{
    pthread_t thread[5];
    char buffer[1024];

    for (int i = 0; i < 5; i++)
    {
        sprintf(buffer, "I am thread %d", i + 1);
        pthread_create(&thread[i], nullptr, handler, (void*)buffer);
        sleep(1);
    }

    while (true)
    {
        std::cout << "I am main thread" << std::endl;
        sleep(1);
    }

    return 0;
} */


void* pthreadFun(void* argv)
{
    const std::string message = (char*)argv;
    int cnt = 10;
    while (cnt)
    {
        std::cout << message << std::endl;
        cnt--;
        sleep(1);
    }

    std::cout << "i finish runing" << std::endl;
    int* ptr = nullptr;
    *ptr = 10;
}

int main()
{
    pthread_t tid[5];
    for (int i = 0; i < 5; i++)
    {
        char buffer[1024];
        sprintf(buffer, "i am thread %d", i + 1);
        pthread_create(&tid[i], nullptr, pthreadFun, (void*)buffer);
        sleep(1);
    }

    while (true)
    {
        std::cout << "main thread runing" << std::endl;
        sleep(1);
    }

    return 0;
}
//当一个线程出现异常的时候，会将整个进程退出